#!/usr/bin/env python

import sys
import argparse
import os
import glob
import csv

parser= argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                                description= """Rename fastq files on the basis of contents file from LIMS

## Example fastq to rename
SLX-7246.D702_D503.C3BY5ACXX.s_2.r_1.fq.gz

## example csv file:
"Pool","Barcode","Sequence","Sample name"
"SLX-7246","D711-D501","TCTCGCGC-TATAGCCT","1"
"SLX-7246","D702-D502","TCCGGAGA-ATAGAGGC","2"
"SLX-7246","D711-D502","TCTCGCGC-ATAGAGGC","5"
""")

parser.add_argument("--csv", "-c", required= True, help= "CSV file relating barcodes to sample names")
parser.add_argument("--fastq", "-f", required= True, nargs= "+", help= "List of fastq files to rename. Glob characters are expanded.")
parser.add_argument("--test", action= "store_true", help= "Only show the renaming. Do not actually rename files")

args= parser.parse_args()

def limsBarcode2FastqBarcode(x):
    """
    Convert the barcode read from csv file to format present in fastq file name
    """
    xfq= x.replace("-", "_")
    return(xfq)

def cleanLibrary_id(x):
    """
    Remove blanks from library_id
    """
    cx= x.replace(" ", "_")
    return(cx)

fastq= []
for x in args.fastq:
    fastq.extend(glob.glob(x))
fastq= sorted(list(set(fastq)))

fin= open(args.csv)
samplesheet= csv.DictReader(fin)

libraries= []
for x in samplesheet:
    id2bar= ( cleanLibrary_id( x["Sample name"] ), limsBarcode2FastqBarcode(x["Barcode"]) )
    libraries.append(id2bar)

## Make sure you have only unique barcodes
barcodes= [x[1] for x in libraries]
if len(barcodes) != len(set(barcodes)):
    sys.exit("Duplicate barcodes")

for fq in fastq:
    for lib in libraries:
        id= lib[0]
        bar= lib[1]
        if ("." + bar + ".") in fq:
            newname= id + "." + fq
            print(fq + "    " + newname)
            if not args.test:
                os.rename(fq, newname)

    
if __name__ == '__main__':
    sys.exit()